<template>
  <div class="app-container">
    <Header title="购物车案例"></Header>
    <Goods 
      v-for="item in list" 
      :key="item.id"
      :id="item.id" 
      :title="item.goods_name" 
      :pic="item.goods_img" 
      :price="item.goods_price"
      :count="item.goods_count"
      :state="item.goods_state"
      @state-change="getNewState"
    >
      <Counter :state="item.goods_state" :num="item.goods_count" @num-change="getNewNum(item, $event)"></Counter>
    </Goods>
    <Footer
      :isfull="fullState"
      :amount="amt"
      :all="total"
      @change-fullstate="getNewFullState"
    ></Footer>
  </div>
</template>

<script>
  import Header from './components/Header/Header.vue'
  import Goods from './components/Goods/Goods.vue'
  import Footer from './components/Footer/Footer.vue'
  import Counter from './components/Counter/Counter.vue'
  import bus from './components/eventBus.js'
  import axios from 'axios'

  export default {
    data() {
      return {
        list: []
      }
    },
    methods: {
      async initCartList() {
        const res = await axios.get('https://www.escook.cn/api/cart')
        const data = res.data
        data.list.forEach(item => {item.goods_state = true})
        this.list = data.list
      },
      getNewState(e) {
        this.list.some(item => {
          if(item.id == e.id) {
            item.goods_state = e.value
            return true
          }
        })
      },
      getNewNum(item, e) {
        item.goods_count = e
      },
      getNewFullState(val) {
        this.list.forEach(item => {
          item.goods_state = val
        })
      }
    },
    created() {
      this.initCartList()
      bus.$on('share', (e) => {
        this.list.some(item => {
          if(item.id === e.id) {
            item.goods_count = e.value
            return true
          }
        })
      })
    },
    computed: {
      fullState() {
        return this.list.every(item => item.goods_state === true)
      },
      amt() {
        return this.list.filter(item => item.goods_state === true).reduce((total, item) => total += item.goods_price * item.goods_count, 0)
      },
      total() {
        return this.list.filter(item => item.goods_state === true).reduce((t, item) => t += item.goods_count, 0)
      }
    },
    components: {
      Header,
      Goods,
      Footer,
      Counter
    }
  }
</script>

<style lang="less" scoped>
.app-container {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>
